#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    startVideoThread();
}

MainWindow::~MainWindow()
{
    delete ui;

    if (m_rtpsthread != nullptr) {
        m_rtpsthread->stopThread();
        delete m_rtpsthread;
        m_video_thread->quit();
        m_video_thread->wait();
        m_video_thread->deleteLater();
        delete m_video_thread;
    }
}

void MainWindow::startVideoThread()
{
    if (!QString(RTSP_ADDR).isEmpty()) {
#if HW_ACC
        m_hwffmpeg_find = new HWFFmpegFind();
        m_hwffmpeg_find->setUrl(QString(RTSP_ADDR));
        connect(m_hwffmpeg_find, &HWFFmpegFind::drawImage, ui->videoWidget, &VideoDisplaySingle::showImage);
        if (m_hwffmpeg_find->init()) {
            m_rtpsthread = new RtpsThread();
            m_rtpsthread->setHWFFmpegFind(m_hwffmpeg_find);
            m_video_thread = new QThread();
            m_rtpsthread->moveToThread(m_video_thread);
            connect(m_video_thread, &QThread::started, m_rtpsthread, &RtpsThread::run);
            m_video_thread->start();
        }
#else
        m_ffmpeg = new FFmpeg();
        m_ffmpeg->setUrl(QString(RTSP_ADDR));
        connect(m_ffmpeg, &FFmpeg::drawImage, ui->videoWidget, &VideoDisplaySingle::showImage);
        if (m_ffmpeg->init()) {
            m_rtpsthread = new RtpsThread();
            m_rtpsthread->setFFmpeg(m_ffmpeg);
            m_video_thread = new QThread();
            m_rtpsthread->moveToThread(m_video_thread);
            connect(m_video_thread, &QThread::started, m_rtpsthread, &RtpsThread::run);
            m_video_thread->start();
        }
#endif
    }
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    ui->videoWidget->setWidget(0, 0, ui->videoWidget->width(), ui->videoWidget->height());
}

